<template>
  <div class="ocr-container">
    <el-container>
      <el-header height="60px">
        <div class="header-content">
          <div class="title">OCR 图像识别系统</div>
          <div class="user-info">
            <span>欢迎，{{ username }}</span>
            <el-button type="text" @click="logout">退出登陆</el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="upload-section">
          <el-upload
            class="upload-box"
            drag
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件</div>
          </el-upload>
          <el-button 
            type="primary" 
            @click="uploadImage" 
            :disabled="!imageFile" 
            :loading="loading"
            style="margin-top: 20px">
            开始识别
          </el-button>
        </div>
        
        <div v-if="previewUrl" class="result-section">
          <!-- OCR识别结果展示 -->
          <div class="result-title">OCR识别结果：</div>
          
          <!-- 文字位置调整选项 -->
          <div class="adjust-options">
            <!-- 快速调整按钮 -->
            <div class="quick-adjust">
              <el-button size="mini" @click="quickAdjustRight(20)">向右 +20px</el-button>
              <el-button size="mini" @click="quickAdjustRight(50)">向右 +50px</el-button>
              <el-button size="mini" @click="resetAdjustments">重置</el-button>
            </div>
            
            <div class="adjust-item">
              <span>水平位置调整: {{ textOffsetX }}px</span>
              <el-slider 
                v-model="textOffsetX"
                :min="-50"
                :max="200"
                :step="5"
                @change="reprocessOcrResults">
              </el-slider>
            </div>
            <div class="adjust-item">
              <span>垂直位置调整: {{ textOffsetY }}px</span>
              <el-slider 
                v-model="textOffsetY"
                :min="-50"
                :max="50"
                @change="reprocessOcrResults">
              </el-slider>
            </div>
            <div class="adjust-item">
              <span>背景透明度: {{ bgOpacity }}</span>
              <el-slider 
                v-model="bgOpacity"
                :min="0"
                :max="1"
                :step="0.1"
                @change="updateTextStyle">
              </el-slider>
            </div>
          </div>
          
          <div class="image-container ocr-result-container">
            <img :src="previewUrl" class="ocr-image" />
            <div class="ocr-text-layer">
              <div 
                v-for="(item, index) in ocrResult" 
                :key="index" 
                class="ocr-text-item"
                :style="{
                  left: item.x + 'px',
                  top: item.y + 'px',
                  width: item.width + 'px',
                  height: item.height + 'px',
                  fontSize: item.fontSize
                }">
                {{ item.str }}
              </div>
            </div>
          </div>
          
          <!-- 完整识别文本 -->
          <div v-if="textOutput" class="full-text-section">
            <div class="result-title">完整识别文本：</div>
            <el-input
              type="textarea"
              :rows="4"
              placeholder="识别结果将在这里显示"
              v-model="textOutput"
              readonly>
            </el-input>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import authConfig from '../config/auth.js'

export default {
  name: 'OcrViewer',
  data() {
    return {
      username: localStorage.getItem('username') || '用户',
      imageFile: null,
      previewUrl: '',
      ocrResult: [],
      textOutput: '',
      loading: false,
      imageWidth: 0,
      imageHeight: 0,
      displayWidth: 0,
      displayHeight: 0,
      // 文字位置调整参数
      textOffsetX: 20,  // 水平方向额外偏移量，默认向右偏移20px
      textOffsetY: 0,   // 垂直方向额外偏移量
      originalOcrResults: [],
      bgOpacity: 0.7 // 背景透明度
    }
  },
  methods: {
    logout() {
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('username')
      this.$router.push('/login')
    },
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLimitSize = file.size / 1024 / 1024 < 10
      
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLimitSize) {
        this.$message.error('图片大小不能超过 10MB!')
      }
      
      return isImage && isLimitSize
    },
    handleFileChange(file) {
      if (file) {
        this.imageFile = file.raw
        this.previewUrl = URL.createObjectURL(this.imageFile)
        
        // 清除之前的OCR结果
        this.ocrResult = []
        
        // 获取图片尺寸
        const img = new Image()
        img.onload = () => {
          this.imageWidth = img.width
          this.imageHeight = img.height
        }
        img.src = this.previewUrl
      }
    },
    uploadImage() {
      if (!this.imageFile) {
        this.$message.warning('请先选择图片')
        return
      }
      
      this.loading = true
      
      // 创建FormData对象
      const formData = new FormData()
      formData.append('file', this.imageFile)
      
      // 发送请求到OCR API
      this.$axios.post(authConfig.apiBaseUrl + '/image_to_ocr', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        this.loading = false
        const data = response.data
        
        if (data && data.json_results) {
          this.ocrResult = []
          this.textOutput = data.text_output || ''
          
          // 保存原始OCR结果
          this.originalOcrResults = JSON.parse(JSON.stringify(data.json_results))
          
          // 等待DOM更新完成后再调整位置
          this.$nextTick(() => {
            // 先获取图片的显示尺寸，然后处理OCR结果
            this.getImageDisplaySize().then(() => {
              // 处理OCR结果
              this.processOcrResults(this.originalOcrResults)
            })
          })
        } else {
          this.$message.error('OCR识别失败，请重试')
        }
      })
      .catch(error => {
        this.loading = false
        console.error('OCR识别出错:', error)
        this.$message.error('OCR服务请求出错，请检查网络连接')
      })
    },
    getImageDisplaySize() {
      return new Promise((resolve) => {
        // 等待图片加载完成并获取显示尺寸
        const checkImage = () => {
          const imgElement = document.querySelector('.ocr-image')
          if (imgElement && imgElement.complete) {
            this.displayWidth = imgElement.clientWidth
            this.displayHeight = imgElement.clientHeight
            resolve()
          } else {
            setTimeout(checkImage, 100) // 等待100ms后再次检查
          }
        }
        checkImage()
      })
    },
    processOcrResults(results) {
      if (!results || !results.length) return
      
      console.log('原始图片尺寸:', this.imageWidth, this.imageHeight)
      console.log('显示尺寸:', this.displayWidth, this.displayHeight)
      
      // 清空当前结果
      this.ocrResult = []
      
      // 计算缩放比例
      const scaleX = this.displayWidth / this.imageWidth
      const scaleY = this.displayHeight / this.imageHeight
      
      // 使用同样的缩放比例
      const scale = Math.min(scaleX, scaleY)
      
      // 计算居中偏移
      const offsetX = (this.displayWidth - this.imageWidth * scale) / 2
      const offsetY = (this.displayHeight - this.imageHeight * scale) / 2
      
      // 调整OCR结果的位置和大小
      results.forEach(item => {
        // 根据高度计算合适的字体大小，约为高度的70%
        const fontSize = Math.max(Math.floor(item.height * scale * 0.7), 12)
        
        // 文字宽度可能比原始框稍宽，向左稍微调整起始位置以居中显示
        const textWidthAdjust = -5; // 向左微调以补偿文字宽度
        
        // 调整X坐标的偏移量，加上用户设置的额外偏移量
        const adjustedX = item.x * scale + offsetX + this.textOffsetX + textWidthAdjust
        const adjustedY = item.y * scale + offsetY + this.textOffsetY
        
        const adjustedItem = {
          ...item,
          x: adjustedX,
          y: adjustedY,
          width: item.width * scale,
          height: item.height * scale,
          str: item.str,
          fontSize: `${fontSize}px`
        }
        this.ocrResult.push(adjustedItem)
      })
      
      console.log('调整后的OCR结果:', this.ocrResult)
    },
    reprocessOcrResults() {
      // 清空当前结果
      this.ocrResult = []
      
      // 重新处理原始结果
      this.processOcrResults(this.originalOcrResults)
    },
    updateTextStyle() {
      // 更新所有文本项的样式
      document.documentElement.style.setProperty('--bg-opacity', this.bgOpacity);
    },
    quickAdjustRight(amount) {
      this.textOffsetX += amount;
      this.reprocessOcrResults();
    },
    resetAdjustments() {
      this.textOffsetX = 20;
      this.textOffsetY = 0;
      this.reprocessOcrResults();
    }
  },
  created() {
    // 初始化CSS变量
    document.documentElement.style.setProperty('--bg-opacity', this.bgOpacity);
  }
}
</script>

<style scoped>
.ocr-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: #409EFF;
  color: white;
  line-height: 60px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info span {
  margin-right: 15px;
}

.el-main {
  padding: 20px;
}

.upload-section {
  text-align: center;
  margin-bottom: 30px;
}

.upload-box {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

.result-section {
  margin-top: 30px;
  width: 100%;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.result-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.image-container {
  position: relative;
  border: 1px solid #dcdfe6;
  overflow: hidden;
  height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.preview-image, .ocr-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.ocr-result-container {
  position: relative;
}

.ocr-text-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.ocr-text-item {
  position: absolute;
  background-color: rgba(0, 0, 0, var(--bg-opacity, 0.7));
  color: #FFFFFF;
  padding: 1px 3px;
  font-size: 14px;
  font-weight: normal;
  box-sizing: border-box;
  display: inline-block;
  text-align: left;
  text-shadow: none;
  white-space: nowrap;
  overflow: visible;
  line-height: 1.2;
  border-radius: 2px;
  letter-spacing: 0.5px;
}

.full-text-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.adjust-options {
  margin-bottom: 20px;
}

.adjust-item {
  margin-bottom: 10px;
}

.adjust-item span {
  margin-right: 10px;
}

.quick-adjust {
  margin-bottom: 10px;
}
</style> 